<?php 
session_start();
$members_id = $_SESSION['id'];
$home = $_SESSION['email'];
$dirupload = "media/" . $home . "/";
$allowedExts = array("jpg", "jpeg", "gif", "png");
$allowedType = array("image/gif", "image/jpeg", "image/png", "image/pjpeg");
$total = 0;
foreach ($_FILES["images"]["error"] as $key => $error) {
    $total++;
    if ($error == UPLOAD_ERR_OK) {
        $ext = end(explode(".", $_FILES["images"]["name"][$key]));
        $img_size = $_FILES["images"]["size"][$key];
        $filename = basename($_FILES['images']['name'][$key]);
        if (($img_size < 5*1024*1024)
        && in_array($_FILES["images"]["type"][$key], $allowedType)
        && in_array($ext, $allowedExts)) {
            do {
                $newname = rand_string(20) . "." . $ext;
            } while (file_exists("../" . $dirupload . $newname));
            move_uploaded_file($_FILES['images']['tmp_name'][$key], "../" . $dirupload . $newname);
            require_once '../model/database.php';
            $conn = connectDB();
            $url = $dirupload . $newname;
            $desc_img = $filename;
            $sql = "INSERT INTO images(members_id, url, name, size, desc_img)
                    VALUES($members_id, '$url', '$filename', $img_size, '$desc_img')";
            mysqli_query($conn, $sql) or die(mysqli_error($conn));
        }
        
    } else {
        $msg .= $_FILES["images"]["name"][$key] . " ERR code: " . $_FILES["images"]["error"][$key] . "<br />";
    }
}
echo $msg;
echo "$total files upload successful";
function rand_string( $length ) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $size = strlen( $chars );
    for( $i = 0; $i < $length; $i++ ) {
        $str .= $chars[ rand( 0, $size - 1 ) ];
    }
    return $str;
}
?>